﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Net;
using System.IO;
using System.Text;

namespace ebay.Jasp
{
    /// <summary>
    ///Jasp 的摘要说明
    /// </summary>
    public class Tools
    {
        #region 输出XML Http头
        /// <summary>
        /// 输出XML Http头
        /// </summary>
        /*public static void HttpHeaderXML()
        {
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.ContentType = "text/xml";
            HttpContext.Current.Response.Expires = 0;
            HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now;
            HttpContext.Current.Response.CacheControl = "no-cache";
            //throw new NotImplementedException();
        }*/
        #endregion

        #region 输出json Http头
        /// <summary>
        ///  输出json Http头
        /// </summary>
        public static void jsonheader()
        {
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.ContentType = "application/json";
            HttpContext.Current.Response.Expires = 0;
            HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now;
            HttpContext.Current.Response.CacheControl = "no-cache";
        }/**/

        #endregion

        #region "获取用户IP地址"
        /// <summary>
        /// 获取用户IP地址
        /// </summary>
        /// <returns></returns>
        /*public static string GetIPAddress()
        {

            string user_IP = string.Empty;
            user_IP = System.Web.HttpContext.Current.Request.UserHostAddress;
            return user_IP;
        }*/
        #endregion

        #region 将UNIX时间戳转换成系统时间/将c# DateTime时间格式转换为Unix时间戳格式

        /// <summary>
        /// 将UNIX时间戳转换成系统时间
        /// </summary>
        /// <param name="timeStamp">UNIX时间戳</param>
        /// <returns>DateTime</returns>
        public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>
        /// 将c# DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time">时间</param>
        /// <returns>int</returns>
        public static int ConvertDateTimeInt(DateTime time)
        {
            int intResult = 0;
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = (int)(time - startTime).TotalSeconds;
            return intResult;
        }

        #endregion

        #region 获取XMl数据
        /// <summary>
        /// 获取XMl数据
        /// </summary>
        /// <param name="url">Http访问地址</param>
        /// <returns>XmlDocument</returns>
        public static XmlDocument GetHttpDownloadDocument(string url)
        {
            try
            {
                System.IO.Stream dataStream = HttpDownload(url);//qidongchuangwei(网吧ID)
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(dataStream);
                return xmldoc;
            }
            catch (Exception ex) { throw ex; }
        }
        private static System.IO.Stream HttpDownload(string url)
        {
            try
            {
                WebRequest webreq = WebRequest.Create(url);
                webreq.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
                HttpWebResponse response = (HttpWebResponse)webreq.GetResponse();
                string contenttype = response.GetResponseHeader("Content-Encoding");
                if (contenttype != null)
                {
                    if (string.Compare(contenttype, "gzip", true) == 0)
                    {
                        return new System.IO.Compression.GZipStream(response.GetResponseStream(),
                            System.IO.Compression.CompressionMode.Decompress, true);
                    }
                    else if (string.Compare(contenttype, "deflate", true) == 0)
                    {
                        return new System.IO.Compression.DeflateStream(response.GetResponseStream(),
                            System.IO.Compression.CompressionMode.Decompress, true);
                    }
                }
                return response.GetResponseStream();
            }
            catch (Exception ex) { throw ex; }
        }

        #endregion

        #region Stream 和 byte[] 之间的转换/将 byte[] 转成 Stream
        /// <summary>
        /// 将 Stream 转成 byte[]
        /// </summary>
        public static byte[] StreamToBytes(System.IO.Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);

            // 设置当前流的位置为流的开始
            stream.Seek(0, System.IO.SeekOrigin.Begin);
            return bytes;
        }

        /// <summary>
        /// 将 byte[] 转成 Stream
        /// </summary>
        public static System.IO.Stream BytesToStream(byte[] bytes)
        {
            System.IO.Stream stream = new System.IO.MemoryStream(bytes);
            return stream;
        }
        #endregion

        #region 向文件写入内容并根据bool append参数决定是改写还是追加 append=false则改写
        /// <summary>
        /// 向文件写入内容并根据bool append参数决定是改写还是追加 append=false则改写
        /// </summary>
        public static void WriteFile(string file, string fileContent, bool append)
        {
            ////System.IO.Directory.GetCurrentDirectory()
            ////string filex = m_filepath + @"\" + file;
            //file = Environment.CurrentDirectory + @"\" + file;
            ////file = "|DataDirectory|" + file; + "\r\n\r\n" + filex + "\r\n\r\n"
            FileInfo info = new FileInfo(file);
            if (!Directory.Exists(info.DirectoryName))
            {
                Directory.CreateDirectory(info.DirectoryName);
            }
            StreamWriter writer = new StreamWriter(file, append, Encoding.GetEncoding("utf-8"));
            try
            {
                try
                {
                    writer.Write(fileContent);
                }
                catch (Exception exception)
                {
                    throw new FileNotFoundException(exception.ToString());
                }
            }
            finally
            {
                writer.Flush();
                writer.Close();
            }
        }
        #endregion
    }
}